package com.kaifamiao.high.thread;

import java.time.LocalTime;
import java.util.concurrent.*;

/**
 * @author lucien-ma
 * @date 2021/10/9
 * @apiNote
 * 阿里编码规范，不建议我们直接只用Executors创建线程池，
 * 所以我们用 ThreadPoolExecutor 和ScheduledThreadPoolExecutor 自己创建常用的线程池
 */
public class Demo11 {
    public static void main(String[] args) {
        // Executors.newCachedThreadPool()
        ThreadPoolExecutor pool1 = new ThreadPoolExecutor(0,
                Integer.MAX_VALUE,
                60L,
                TimeUnit.SECONDS,
                new SynchronousQueue<>());

        // Executors.newFixedThreadPool(2);
        ThreadPoolExecutor pool2 = new ThreadPoolExecutor(2, 2,
                0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());

        // Executors.newSingleThreadExecutor();
        ThreadPoolExecutor pool3 = new ThreadPoolExecutor(1, 1,
                0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());

        // Executors.newScheduledThreadPool(2);
        ScheduledThreadPoolExecutor pool4 = new ScheduledThreadPoolExecutor(2);

        // 测试
        System.out.println("当前时间为：" + LocalTime.now());
        for (int i = 0; i < 10; i++) {
            int number = i;
            pool3.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("当前时间：" + LocalTime.now() +
                            ", 线程：" + Thread.currentThread().getName() +
                            ", 序号：" + number);
                    try {
                        Thread.currentThread().sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        // 执行完任务后关闭线程
        pool1.shutdown();
        pool2.shutdown();
        pool3.shutdown();
        pool4.shutdown();
    }
}
